package com.hmdp.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     *
     * @return
     */
    @Override
    public Result queryList() {
        //查询redis中是否有对应数据
        String shopTypeStr = stringRedisTemplate.opsForValue().get(SystemConstants.CACHE_SHOP_TYPE);


        //如果有,则直接返回
        if (StrUtil.isNotBlank(shopTypeStr)){
            List<ShopType> shopTypeList = JSONUtil.parseArray(shopTypeStr).toList(ShopType.class);
            return Result.ok(shopTypeList);
        }

        //如果没有,从数据库查询数据返回,并将数据添加入redis中
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if (shopTypeList != null && shopTypeList.size() > 0){
            //在数据库中查询到后
            //添加入redis
            String jsonStr = JSONUtil.toJsonStr(shopTypeList);
            stringRedisTemplate.opsForValue().set(SystemConstants.CACHE_SHOP_TYPE,jsonStr);
            //返回
            return Result.ok(shopTypeList);
        }
        //如果数据库查询不到,报错
        return Result.fail("店铺类型不在");
    }
}
